// dao/apiKeys.js
import { connect } from '../db'

// 获取所有API密钥
export function getAllApiKeys() {
  const db = connect()
  return db.prepare('SELECT * FROM api_keys ORDER BY created_at DESC').all()
}

// 添加新API密钥
export function addApiKey(name, key, description = '', enabled = 0) {
  const db = connect()
  const now = Date.now()
  const info = db.prepare(
    'INSERT INTO api_keys (name, key, description, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)'
  ).run(name, key, description, enabled, now, now)
  return info
}

// 更新API密钥
export function updateApiKey(id, { name, key, description, enabled }) {
  const db = connect()
  const now = Date.now()
  const info = db.prepare(
    'UPDATE api_keys SET name = ?, key = ?, description = ?, enabled = ?, updated_at = ? WHERE id = ?'
  ).run(name, key, description, enabled, now, id)
  return info
}

// 根据ID删除API密钥
export function deleteApiKey(id) {
  const db = connect()
  const info = db.prepare('DELETE FROM api_keys WHERE id = ?').run(id)
  return info
}

// 启用/禁用API密钥
export function toggleApiKeyStatus(id, enabled) {
  const db = connect()
  const now = Date.now()
  const info = db.prepare(
    'UPDATE api_keys SET enabled = ?, updated_at = ? WHERE id = ?'
  ).run(enabled ? 1 : 0, now, id)
  return info
}

// 获取随机启用的API密钥
export function getRandomEnabledApiKey() {
  const db = connect()
  const enabledKeys = db.prepare('SELECT * FROM api_keys WHERE enabled = 1').all()

  if (enabledKeys.length === 0) {
    return null
  }

  // 随机选择一个启用的密钥
  const randomIndex = Math.floor(Math.random() * enabledKeys.length)
  return enabledKeys[randomIndex]
}

// 根据ID获取单个API密钥
export function getApiKeyById(id) {
  const db = connect()
  return db.prepare('SELECT * FROM api_keys WHERE id = ?').get(id)
}
